import mitt from "mitt";

export declare type EventBusHandler<T = unknown> = (event: T) => void;

/**
 * 事件方法
 */
export interface EventBusReturn {
    /**
     * 订阅事件
     * @param key 事件名称
     * @param handler 事件数据
     */
    on<T>(key: string, handler: EventBusHandler<T>): void;

    /**
     * 发送事件
     * @param key 事件名称
     * @param event 事件数据
     */
    emit<T>(key: string, event: T): void;

    /**
     * 取消订阅
     * @param key 事件名称
     * @param handler 方法
     */
    off(key: string, handler: Function): void;
}

//全局事件
const eventBus = mitt();
const onEvents: any = {};

/**
 * 全局事件总线
 */
export function useEventBus(): EventBusReturn {

    return {
        off(key: string, handler: any): void {
            if (!onEvents[key]) {
                return;
            }
            for (let i = 0; i < onEvents[key].length; i++) {
                let data= onEvents[key][i];
                if (data.HandlerAction == handler) {
                    eventBus.off(key, data.OnAction);
                    onEvents[key].splice(i, 1);
                    break;
                }
            }
        },
        emit<T>(key: string, event: T): void {
            eventBus.emit(key, event);
        },
        on<T>(key: string, handler: EventBusHandler<T>) {
            const action = (data: any) => {
                handler(data as T);
            };
            if (!onEvents[key]) {
                onEvents[key] = [];
            }
            onEvents[key].push({
                HandlerAction: handler,
                OnAction: action
            });
            eventBus.on(key, action);
        }
    }
}